home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2574 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.2 KB  |  71 lines

  1. Path: EU.net!sun4nl!ittpub!ittpub!nntp
  2. Newsgroups: comp.lang.c++
  3. Subject: Re: maybe a FAQ... how to ensure the order in which global constructors 
  4. Message-ID: <1996Jan18.152308.1748@ittpub>
  5. From: wil@ittpub.nl (Wil Evers)
  6. Date: 18 Jan 96 15:23:08 WET
  7. References: <4d3gni$pmp@inet01.colgate.edu>
  8. Distribution: world
  9. Nntp-Posting-Host: lintilla
  10.  
  11. In article <4d3gni$pmp@inet01.colgate.edu> jwilson@center.colgate.edu  
  12. (KRSNA CONSCIOUSNESS NOW) writes:
  13.  
  14. > [snip]
  15. > I subclassed Handle to RegisterHandle, and as part of the constructor of
  16. > RegisterHandle, the new RegisterHandle is automatically added to a
  17. > global Registry. Or I would so; this only works if the global registry 
  18. > has been constructed prior to the construction of the RegisterHandle. 
  19. > [snip]
  20. > Is there a mechanism for ensuring that global constructors are called in
  21. > a certain order?
  22.  
  23. Global objects are constructed in order of definition in their translation  
  24. units (source file). There is no guarantee of any ordering when two global  
  25. objects are defined in different translation units.
  26.  
  27. You can force a particular object to be initialized (yes, initialized,  
  28. which is not the same as constructed) by using what is called the  
  29. nifty_counter idiom. If you put this in some header file (say, "nifty.h"):
  30.  
  31.     class nifty_counter {
  32.         static int cnt = 0;
  33.     public :
  34.         nifty_counter();
  35.         ~nifty_counter();
  36.     };
  37.  
  38.     static nifty_counter nifty;
  39.  
  40. and this in some implementation file:
  41.  
  42.     int nifty_counter::cnt = 0;
  43.  
  44.     nifty_counter::nifty_counter()
  45.     {
  46.         if (cnt++ == 0) {
  47.             // initialize here
  48.         }
  49.     }
  50.  
  51.     nifty_counter::~nifty_counter()
  52.     {
  53.         if (--cnt == 0) {
  54.             // uninitialize here
  55.         }
  56.     }
  57.  
  58. then every object defined below an #include "nifty.h" can count on the  
  59. fact that the initialization took place before its constructor is run.
  60.  
  61. Unfortunately, this is only half the story, since the initialization you  
  62. would like to do might interfere with the constructor of the object you're  
  63. trying to initialize. Some special tricks, like giving the global object a  
  64. 'do nothing' constructor and a separate init() member function or  
  65. constructing the object via 'placement new' in a raw memory area, are  
  66. needed to make this work properly.
  67.  
  68. Hope this helps,
  69.  
  70. - Wil
  71.